//
//  HttpClient.m
//  YangLiuQing(OC)
//
//  Created by wxc on 2018/2/1.
//  Copyright © 2018年 wxc. All rights reserved.
//

#import "HttpClient.h"

@implementation HttpClient


/*
 *
 *    菊花 GET 请求
 */
+(void)PostUrl:(NSString *)url parameters:(NSDictionary *)params success:(void (^)(id json,NSInteger flag))success fail:(void (^)(NSError *error))fail{
    
    
//    dispatch_async(dispatch_get_main_queue(), ^{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    if (![params[@"prompt"] isEqualToString:@""])
    {
        [SVProgressHUD showWithStatus:params[@"prompt"]==nil ? @"正在加载" : params[@"prompt"]];
    }
    
        // 2.创建一个网络请求
        NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        // 3.获得会话对象
        NSURLSession *session = [NSURLSession sharedSession];
        session.configuration.timeoutIntervalForRequest = 60;
        // 4.根据会话对象，创建一个Task任务：
        NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 
            dispatch_async(dispatch_get_main_queue(), ^{
      
                if (success) {
                    if (data)
                    {
                        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        [SVProgressHUD dismissWithDelay:1];
                        success(jsonObject,[[jsonObject objectForKey:@"code"] integerValue]);
                    }
                    else
                    {
                        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                        [SVProgressHUD showErrorWithStatus:@"连接服务器超时，请稍后重试"];
                        [SVProgressHUD dismissWithDelay:2];
                    }
                }
                else
                {
                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                    [SVProgressHUD showErrorWithStatus:@"连接服务器超时，请稍后重试"];
                    [SVProgressHUD dismissWithDelay:2];
                }
                
            });
            
        }];
        // 5.最后一步，执行任务（resume也是继续执行）:
        [sessionDataTask resume];
//    });
    
}


/*
 *
 *   无 菊花 GET 请求
 */
+(void)PostUrl_svpdiss:(NSString *)url success:(void (^)(id json,NSInteger flag))success fail:(void (^)(NSError *error))fail{

    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (success)
            {
                if (data)
                {
                    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    [SVProgressHUD dismissWithDelay:1];
                    success(jsonObject,[jsonObject[@"code"] integerValue]);
                }
                else
                {
                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                    [SVProgressHUD showErrorWithStatus:@"连接服务器超时，请稍后重试"];
                    [SVProgressHUD dismissWithDelay:2];
                }
            }
            else
            {
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                [SVProgressHUD showErrorWithStatus:@"连接服务器超时，请稍后重试"];
                [SVProgressHUD dismissWithDelay:2];
            }
        });
        
    }];
    [sessionDataTask resume];
    
}


/*
 *
 *   POST
 */

+ (void)HttpPost:(NSString *)url parameters:(NSDictionary *)dic message:(NSString *)msg success:(void (^)(id, NSInteger))success fail:(void (^)(NSError *))fail
{
    if (msg)
    {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showWithStatus:msg];
    }
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 60;
    [session POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismissWithDelay:1];
        NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init];
        [dictionary setValuesForKeysWithDictionary:[NSDictionary changeType:responseObject]];
        success(dictionary,[dictionary[@"code"] integerValue]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error)
        {
            [SVProgressHUD dismissWithDelay:1];
            fail(error);
        }

    }];
}

/*
 *
 *   POST 上传图片
 */

+ (void)HttpPostImgWithURL:(NSString *)url
                 Imagename:(NSString *)name
                 ImageData:(NSData *)image
            withParameters: (NSDictionary *) dic
      withUIViewController:(UIViewController *)viewController
     ImgCompressionQuality:(CGFloat)compressionQuality
       UpLoadProgressBlock:(void (^)(float Progress))ProgressBlock
         UpLoadWithSuccess:(void (^)(id result))success
         UpLoadWithFailure:(void (^)(NSError *error))failure
             networkError : (void (^)(BOOL isNetworkError))networkError;
{
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@"正在上传..."];
    // maskType:SVProgressHUDMaskTypeGradient
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 60;
    [session POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        NSData *imgData =image;
        // NSData *imgData = [NSKeyedArchiver archivedDataWithRootObject:image];
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMdd"];
        NSString *dateString = [formatter stringFromDate:date];
        
        int num = (arc4random() % 10000);
        NSString *fileName = [NSString stringWithFormat:@"%@%.4d.png",dateString,num];
        NSLog(@"%@",fileName);
        [formData appendPartWithFileData:imgData name:@"image" fileName:fileName mimeType:@"image/png"];
        //        for (UIImage *image_photo in image) {
        //
        //            NSData *imgData =UIImageJPEGRepresentation(image, compressionQuality);
        //
        //            NSDate *date = [NSDate date];
        //            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        //            [formatter setDateFormat:@"yyyyMMdd"];
        //            NSString *dateString = [formatter stringFromDate:date];
        //
        //            int num = (arc4random() % 10000);
        //            NSString *fileName = [NSString stringWithFormat:@"%@%.4d.png",dateString,num];
        //            NSLog(@"%@",fileName);
        //            [formData appendPartWithFileData:imgData name:@"file" fileName:fileName mimeType:@"image/png"];
        //
        //
        //        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //    [viewController.view setProgress:uploadProgress.fractionCompleted];
            ProgressBlock(uploadProgress.fractionCompleted);
        });
        
        //打印下上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismissWithDelay:1];
        NSMutableDictionary *dictionary=[[NSMutableDictionary alloc]init];
        [dictionary setValuesForKeysWithDictionary:[NSDictionary changeType:responseObject]];
        success(dictionary);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            [SVProgressHUD dismissWithDelay:1];
            failure(error);
        }
    }];
    
}
@end
